﻿using System;
using System.Globalization;
using System.Threading;

using NanoMvvm.Collections;

namespace NanoMvvm
{
    public class LocalizationHelper
    {
        private readonly WeakCollection<PropertyObservableBase> objectBag;

        private CultureInfo currentUiCulture;

        internal LocalizationHelper()
        {
            objectBag = new WeakCollection<PropertyObservableBase>();

            currentUiCulture = Thread.CurrentThread.CurrentUICulture;
            NotifyViewModels(currentUiCulture);
        }

        public event EventHandler CultureChanged;

        public CultureInfo CurrentUiCulture
        {
            get
            {
                return currentUiCulture;
            }

            set
            {
                if (!Equals(value, currentUiCulture))
                {
                    currentUiCulture = value;

                    Thread.CurrentThread.CurrentUICulture = value;

                    NanoMvvmFramework.Instance.Synchronization.Main.Send(_ => { Thread.CurrentThread.CurrentUICulture = value; }, null);

                    NotifyViewModels(value);

                    OnCultureChanged();
                }
            }
        }

        public CultureInfo GetCurrentThreadCulture()
        {
            return CultureInfo.CurrentCulture;
        }

        internal void RegisterViewModel(PropertyObservableBase obj)
        {
            objectBag.Add(obj);
        }

        private void OnCultureChanged()
        {
            EventHandler handler = CultureChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        private void NotifyViewModels(CultureInfo newCulture)
        {
            foreach (var vm in objectBag)
            {
                vm.RefreshUiCulture(newCulture);
            }
        }
    }
}